package com.k2.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.k2.common.utils.HttpUtils;
import com.k2.common.vo.UserRegisterVo;
import com.k2.gulimall.member.service.MemberLevelService;
import com.k2.gulimall.member.service.MemberLoginLogService;
import com.k2.gulimall.member.service.MemberStatisticsInfoService;
import com.k2.gulimall.member.utils.HttpClientUtils;
import com.k2.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.k2.common.utils.PageUtils;
import com.k2.common.utils.Query;

import com.k2.gulimall.member.dao.MemberDao;
import com.k2.gulimall.member.entity.MemberEntity;
import com.k2.gulimall.member.service.MemberService;

import javax.servlet.http.HttpSession;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberStatisticsInfoService memberStatisticsInfoService;
    @Autowired
    MemberLevelService memberLevelService;
    @Autowired
    MemberLoginLogService memberLoginLogService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<MemberEntity>();
        if (params.get("username")!=null&&params.get("username").toString().length()>0) {
            queryWrapper.like("username", params.get("username"));
        }
        if (params.get("mobile")!=null&&params.get("mobile").toString().length()>0) {
            queryWrapper.eq("mobile", params.get("mobile"));
        }
        if (params.get("createTime")!=null&&params.get("createTime").toString().length()>0) {
            try {
                String dateTime = params.get("createTime").toString();
                dateTime = dateTime.replace("Z", " UTC");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                String dateString = df.format(new Date());
                Date time = format.parse(dateTime);
                String result = df.format(time);
                queryWrapper.between("create_time",result,df.parse(dateString));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (params.get("levelnamme")!=null&&params.get("levelnamme").toString().length()>0) {
            queryWrapper.eq("level_id", params.get("levelnamme"));
        }
        //只查询状态为 0正常、1锁定 的用户
        queryWrapper.le("status",1);
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * 根据用户名、邮箱、手机号查询用户
     * @param memberEntity
     * @return
     */
    @Override
    public List<MemberEntity> getUserName(MemberEntity memberEntity) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<MemberEntity>();
        queryWrapper.eq("username",memberEntity.getUsername());
        List<MemberEntity> memberEntityList = this.baseMapper.getUserName(queryWrapper);
        return memberEntityList;
    }

    @Override
    public List<MemberEntity> getUserEmail(MemberEntity memberEntity) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<MemberEntity>();
        queryWrapper.or().eq("email",memberEntity.getEmail());
        List<MemberEntity> memberEntityList = this.list(queryWrapper);
        return memberEntityList;
    }

    @Override
    public List<MemberEntity> getUserMobile(MemberEntity memberEntity) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<MemberEntity>();
        queryWrapper.or().eq("mobile",memberEntity.getMobile());
        List<MemberEntity> memberEntityList = this.list(queryWrapper);
        return memberEntityList;
    }

    /**
     * 通过用户等级id查询 是否有用户正在使用该等级
     * @param ids
     * @return
     */
    @Override
    public List<MemberEntity> getUserlevelId(Long[] ids) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<MemberEntity>();
        queryWrapper.in("level_id", Arrays.asList(ids));
        return this.list(queryWrapper);
    }

    @Override
    public MemberEntity getUserSocialUid(String socialUid) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<MemberEntity>();
        queryWrapper.or().eq("social_uid",socialUid);
        MemberEntity memberEntityList = this.getOne(queryWrapper);
        return memberEntityList;
    }

    /**
     * 批量修改用户状态
     * @param ids
     * @param status 0正常（解锁）、1锁定、2删除
     * @return
     */
    @Override
    public boolean batchdelete(String ids,Integer status) {
        UpdateWrapper<MemberEntity> updateWrapper = new UpdateWrapper<MemberEntity>();
        //修改值
        MemberEntity memberEntity = new MemberEntity();
        if(status == 0){
            memberEntity.setStatus(0);
        }else if (status == 1){
            memberEntity.setStatus(1);
        }else{
            memberEntity.setStatus(2);
        }
        //修改条件
        updateWrapper.in("id",ids);
        return this.update(memberEntity,updateWrapper);
    }


    @Override
    public MemberEntity login(SocialUser socialUser,UserRegisterVo userRegisterVo) throws Exception {
        //具有登录和注册逻辑
        String uid = socialUser.getUid();
        //1、判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity != null) {
            //这个用户已经注册过
            //更新用户的访问令牌的时间和access_token
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());

            //添加统计信息
            userRegisterVo.setUserName(memberEntity.getUsername()!=null?memberEntity.getUsername():null);
            userRegisterVo.setAccessToken(socialUser.getAccess_token());
            memberLoginLogService.addmemberLoginLog(userRegisterVo);
            return memberEntity;
        } else {
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity register = new MemberEntity();
            //3、查询当前社交用户的社交账号信息（昵称、性别等）
            Map<String,String> query = new HashMap<>();
            query.put("access_token",socialUser.getAccess_token());
            query.put("uid",socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

            if (response.getStatusLine().getStatusCode() == 200) {
                //查询成功
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                String profileImageUrl = jsonObject.getString("profile_image_url");

                register.setNickname(name);
                register.setGender("m".equals(gender)?1:0);
                register.setHeader(profileImageUrl);
                register.setCreateTime(new Date());
                register.setSocialUid(socialUser.getUid());
                register.setAccessToken(socialUser.getAccess_token());
                register.setExpiresIn(socialUser.getExpires_in());
                register.setStatus(0);//默认状态
                register.setGrowth(0);//默认成长值
                register.setIntegration(0);//默认积分
                register.setLevelId(memberLevelService.getMemberLevelToDefault().getId());//默认等级

                //把用户信息插入到数据库中
                this.baseMapper.insert(register);

                //添加统计信息
                userRegisterVo.setUserName(register.getUsername());
                userRegisterVo.setAccessToken(socialUser.getUid());
                memberStatisticsInfoService.addmemberStatisticsInfo(userRegisterVo);

            }
            return register;
        }
    }

    @Override
    public MemberEntity login(String accessTokenInfo,UserRegisterVo userRegisterVo) {

        //从accessTokenInfo中获取出来两个值 access_token 和 oppenid
        //把accessTokenInfo字符串转换成map集合，根据map里面中的key取出相对应的value
        Gson gson = new Gson();
        HashMap accessMap = gson.fromJson(accessTokenInfo, HashMap.class);
        String accessToken = (String) accessMap.get("access_token");
        String openid = (String) accessMap.get("openid");

        //3、拿到access_token 和 oppenid，再去请求微信提供固定的API，获取到扫码人的信息
        //TODO 查询数据库当前用用户是否曾经使用过微信登录

        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", openid));

        if (memberEntity == null) {
            System.out.println("新用户注册");
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            //发送请求
            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultUserInfo==========" + resultUserInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //解析json
            HashMap userInfoMap = gson.fromJson(resultUserInfo, HashMap.class);
            String nickName = (String) userInfoMap.get("nickname");      //昵称
            Double sex = (Double) userInfoMap.get("sex");        //性别
            String headimgurl = (String) userInfoMap.get("headimgurl");      //微信头像

            //把扫码人的信息添加到数据库中
            memberEntity = new MemberEntity();
            memberEntity.setNickname(nickName);
            memberEntity.setGender(Integer.valueOf(Double.valueOf(sex).intValue()));
            memberEntity.setHeader(headimgurl);
            memberEntity.setCreateTime(new Date());
            memberEntity.setSocialUid(openid);

            memberEntity.setStatus(0);//默认状态
            memberEntity.setGrowth(0);//默认成长值
            memberEntity.setIntegration(0);//默认积分
            memberEntity.setLevelId(memberLevelService.getMemberLevelToDefault().getId());//默认等级



            // register.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.insert(memberEntity);


            //添加统计信息
            userRegisterVo.setUserName(memberEntity.getUsername());
            userRegisterVo.setAccessToken(openid);//社交登陆id
            memberStatisticsInfoService.addmemberStatisticsInfo(userRegisterVo);


        }else{

        }
        return memberEntity;
    }



}